//
// Created by grant on 9/20/18.
//

#include "http_win.h"

#ifdef WINDOWS


#include <stdio.h>
#include <string.h>
#include <winsock.h>
#include <stdlib.h>

void http_get(char *url){
    WSADATA WsaData;
    SOCKET socketfd;
    SOCKADDR_IN addr;
    HOSTENT *pURL;
    int i=0;
    char myurl[BUFSIZ];
    char *pHost =0,* pGet =0;
    char host[BUFSIZ],GET[BUFSIZ];
    char Header[BUFSIZ];
    FILE * pf;

    static char text[BUFSIZ];

    if (WSAStartup(MAKEWORD(2,2),&WsaData))
    {
        printf("The socket failed");
        return;
    }
    strcpy(myurl,url);

    for (i=0,pHost= myurl;*pHost!='/'&&*pHost!='/0';pHost++,i++){
        host[i] = *pHost;
    }
    host[i]='/0';
    strcpy(GET,pHost);
    strnset(Header,'/0',BUFSIZ);


    socketfd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
    pURL = gethostbyname(host);

    addr.sin_addr.s_addr = *((unsigned long *)pURL->h_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);



    strcat(Header,"GET / ");
    strcat(Header,GET);
    strcat(Header,"HTTP/1.1/r/n");
    strcat(Header,"Accept: */*/r/n");
    strcat(Header,"Accept-Language: zh-cn/r/n");
    strcat(Header,"User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2)/r/n");
    //strcat(Header,"Accept-Encoding: gzip, deflate/r/n");
    strcat(Header,"Host: ");
    strcat(Header,host);
    strcat(Header,"/r/nConnection: Keep-Alive/r/n");

    strcat(Header,"/r/n/r/n");

    connect(socketfd,(SOCKADDR *)&addr,sizeof(addr));
    send(socketfd,Header,strlen(Header),0);
    printf("%s",Header);
    pf = fopen("1.txt","w");
    while(recv(socketfd,text,BUFSIZ,0)>0){
        printf("%s",text);
        fputs(text,pf);
        strnset(text,'/0',BUFSIZ);
    }
    fclose(pf);
    closesocket(socketfd);
    WSACleanup();


}

#endif
